package com.xiaolu.xiaoluaicodebackend.service.impl;

import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;

import com.xiaolu.xiaoluaicodebackend.constant.CacheKeyConstant;
import com.xiaolu.xiaoluaicodebackend.model.vo.CaptchaVO;
import com.xiaolu.xiaoluaicodebackend.service.CaptchaService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;


import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class CaptchaServiceImpl implements CaptchaService {


    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public CaptchaVO getCaptcha() {
        //设置宽高位数
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        //设置类型
        specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
        //获取验证码图片上的文本内容，并把它转为小写形式。
        String captchaCode = specCaptcha.text().toLowerCase();
        //将二进制数据（如图像）转化为文本格式的方式。通过这种转换，图片可以直接嵌入到网页或其他应用中，无需单独的图片文件。
        String captchaImage = specCaptcha.toBase64();
        //Key的唯一
        String captchaKey = UUID.randomUUID().toString();
        // 把验证码存入 Redis 并且设置 1 分钟过期
        ValueOperations<String, String> valueOps = stringRedisTemplate.opsForValue();
        valueOps.set(String.format(CacheKeyConstant.CAPTCHA_CODE_KEY,captchaKey),captchaCode,5, TimeUnit.MINUTES);
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setCaptchaKey(captchaKey);
        captchaVO.setCaptchaImage(captchaImage);
        return captchaVO;
    }
}
